import 'dart:ffi';
import 'dart:io';

import 'package:ffi/ffi.dart';

// 模拟的结构体和函数定义，用于在无法加载真实库时提供基本功能
final class FunASRModelConfig extends Struct {
  external Pointer<Utf8> model_dir;
  external Pointer<Utf8> quantize;
  external Pointer<Utf8> bladedisc;
  external Pointer<Utf8> vad_dir;
  external Pointer<Utf8> vad_quant;
  external Pointer<Utf8> punc_dir;
  external Pointer<Utf8> punc_quant;
  external Pointer<Utf8> itn_dir;
  external Pointer<Utf8> lm_dir;
}

// 模拟的ASR FFI接口，不实际调用任何库
class AsrFFIMock {
  static final AsrFFIMock _instance = AsrFFIMock._internal();
  factory AsrFFIMock() => _instance;
  AsrFFIMock._internal();

  bool _initialized = false;

  void init() {
    // 模拟初始化过程
    print("Mock FFI initialized");
    _initialized = true;
  }

  // 模拟初始化ASR模型
  Pointer<Void> initAsrModel({
    String? modelDir,
    String? quantize,
    String? bladedisc,
    String? vadDir,
    String? vadQuant,
    String? puncDir,
    String? puncQuant,
    String? itnDir,
    String? lmDir,
  }) {
    if (!_initialized) {
      throw Exception("FFI not initialized");
    }

    print("Mock ASR model initialized with modelDir: $modelDir");
    // 返回一个模拟的句柄
    return Pointer<Void>.fromAddress(0x12345678);
  }

  // 模拟执行语音识别
  String recognize(
    Pointer<Void> handle,
    String audioFilePath,
    int samplingRate,
  ) {
    if (!_initialized) {
      throw Exception("FFI not initialized");
    }

    print(
      "Mock recognition for file: $audioFilePath with sampling rate: $samplingRate",
    );

    // 根据文件名返回不同的模拟结果
    if (audioFilePath.contains('asr_example_zh.wav')) {
      return "模拟识别结果：今天天气不错，适合出门散步。";
    } else if (audioFilePath.contains('vad_example.wav')) {
      return "模拟识别结果：你好，这是一个测试语音识别的示例。";
    } else {
      return "模拟识别结果：语音识别已完成。";
    }
  }

  // 模拟释放资源
  void uninit(Pointer<Void> handle) {
    if (!_initialized) {
      throw Exception("FFI not initialized");
    }

    print("Mock ASR resources released");
  }
}
